package com.ds.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ds.context.JDSActionContext;
import com.ds.esd.bean.MethodConfig;
import com.ds.esd.custom.CustomViewFactory;
import com.ds.web.RequestMethodBean;
import com.ds.web.RequestParamBean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashSet;

@Component
public class CustomJsonInterceptor extends BaseInterceptor {
    public static final String CUSSCLASSNAME = "_currClassName_";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            MethodConfig methodConfig = (MethodConfig) JDSActionContext.getActionContext().getContext().get(CustomViewFactory.MethodBeanKey);
            boolean json = false;
            if (methodConfig != null) {
                LinkedHashSet<RequestParamBean> paramBeans = methodConfig.getParamSet();
                for (RequestParamBean paramBean : paramBeans) {
                    if (paramBean.getJsonData()) {
                        json = true;
                    }
                }
            }
            if (json) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                RequestMethodBean methodBean = findMethodBean(request.getRequestURI());
                if (methodBean == null) {
                    methodBean = new RequestMethodBean(handlerMethod.getMethod());
                }
                Object object = invokMethod(methodBean, request, response);
                if (methodBean.getResponseBody() != null) {
                    this.sendJSON(response, JSONObject.toJSONString(object));
                } else {
                    this.sendJSON(response, object.toString());
                }
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


}